var path = require("path");
var express = require("express");
var cookieParse = require("cookie-parser");
var expressSession = require("express-session");
var passport = require("passport");
var connectEnsure = require("connect-ensure-login");

var app = express();
app.use(express.static("static"));
app.use(cookieParse());
app.use(expressSession({
    secret: "suijishuzi",
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 1200000 }
}))

//使用passport
app.use(passport.initialize());
app.use(passport.session());

var mongoose = require("mongoose");
mongoose.connect("127.0.0.1/news");

// 设置渲染模板
var exphbs = require("express-handlebars");
app.set("views", path.join(__dirname, "views"));
// 设置渲染引擎
app.engine(".hbs", exphbs({
    layoutsDir: "views/layouts",
    defaultLayout: "main", //默认转到main.hbs
    extname: ".hbs"
}));

//配置引擎
app.set("view engine", ".hbs");

// 引入路由（中间件）
var routerLogin = require("./router/login");
var routerMain = require("./router/main");
var routerEditor = require("./router/editor");
var routerTravel = require("./router/travel");
app.use("/", routerLogin);
app.use("/", routerMain);
app.use("/", connectEnsure.ensureLoggedIn("/login"), routerEditor);
app.use("/", connectEnsure.ensureLoggedIn("/login"), routerTravel);

// 如果找不到该路径，则跳转到另一个路由，该路由产生404错误
app.use(function(req, res, next) {
    var err = new Error();
    err.status = 404;
    next(err);
});
//处理所有产生错误的路由,返回一个渲染错误的页面
app.use(function(err, req, res, next) {
    var code = err.status || 500,
        message = code === 404 ? res.__("error.404_1") : res.__("error.404_2");
    res.status(code);
    res.render("error", {
        layout: "other",
        code: code,
        message: message
    });
});
app.listen(8888);
console.log("新闻评论开始")